//
//  ScanViewController.m
//  Scan
//
//  Created by Timmy on 16/8/17.
//  Copyright © 2016年 任雨婷. All rights reserved.
//

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ScanView.h"

@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (strong, nonatomic) ScanView *aView;//

@property (strong, nonatomic) UIView *boxView;//扫描框
@property (nonatomic) BOOL isReading;//正在扫描的标志位
@property (nonatomic) BOOL isTorchON;//闪光灯标志位
@property (strong, nonatomic) CALayer *scanLayer;//扫描线
@property (strong,nonatomic)NSTimer *scanTimer;
//捕捉会话
@property(nonatomic,strong)AVCaptureSession *captureSession;
//展示layer
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;

-(BOOL)startReading;
-(void)stopReading;

@end

@implementation ScanViewController

-(void)loadView
{
    self.aView = [[ScanView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.aView;
    [self.aView.startBtn addTarget:self action:@selector(startStopReading:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.aView.flashButton addTarget:self action:@selector(turnTorchOn:) forControlEvents:UIControlEventTouchUpInside];
    _captureSession = nil;
    _isReading = NO;
    _isTorchON = NO;
}

- (void)startStopReading:(id)sender {
    if (!_isReading) {
        if ([self startReading]) {
            [self.aView.startBtn setTitle:@"停止" forState:UIControlStateNormal];
            [self.aView.lblStatus setText:@"正在扫描"];
        }
    }
    else{
        [self stopReading];
        [self.aView.startBtn setTitle:@"开始" forState:UIControlStateNormal];
        [self.aView.lblStatus setText:@""];
    }
    _isReading = !_isReading;
}

- (BOOL)startReading {
    NSError *error;
    
    //初始化捕捉设备（AVCaptureDevice），类型为AVMediaTypeVideo
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //用captureDevice创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    
    //创建媒体数据输出流
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    
    //实例化捕捉会话
    _captureSession = [[AVCaptureSession alloc] init];
    
    //将输入流添加到会话
    [_captureSession addInput:input];
    
    //将媒体输出流添加到会话中
    [_captureSession addOutput:captureMetadataOutput];
    
    //创建串行队列，并加媒体输出流添加到队列当中
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    //设置代理
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    
    //设置输出媒体数据类型为QRCode（二维码） EAN13（商品条形码 比如69开头）其他类型自己添加
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,nil]];
    
    //实例化预览图层
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    
    //设置预览图层填充方式
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    //设置图层的frame
    [_videoPreviewLayer setFrame:self.aView.viewPreview.layer.bounds];
    
    //将图层添加到预览view的图层上
    [self.aView.viewPreview.layer addSublayer:_videoPreviewLayer];
    
    //设置扫描范围
    captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
    
    //扫描框
    _boxView = [[UIView alloc] initWithFrame:CGRectMake(self.aView.viewPreview.bounds.size.width * 0.2f, self.aView.viewPreview.bounds.size.height * 0.2f, self.aView.viewPreview.bounds.size.width - self.aView.viewPreview.bounds.size.width * 0.4f, self.aView.viewPreview.bounds.size.height - self.aView.viewPreview.bounds.size.height * 0.4f)];
    _boxView.layer.borderColor = [UIColor whiteColor].CGColor;
    _boxView.layer.borderWidth = 1.0f;
    
    [self.aView.viewPreview addSubview:_boxView];
    
    //扫描线
    _scanLayer = [[CALayer alloc] init];
    _scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 3);
    _scanLayer.backgroundColor = [UIColor redColor].CGColor;
    
    [_boxView.layer addSublayer:_scanLayer];
    
    self.scanTimer = [NSTimer scheduledTimerWithTimeInterval:0.06f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    [self.scanTimer fire];
    
    //开始扫描
    [_captureSession startRunning];
    return YES;
}



#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        
        //判断回传的数据类型
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode] ||[[metadataObj type] isEqualToString:AVMetadataObjectTypeEAN13Code])
        {
            [self.aView.lblStatus performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
            [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
            _isReading = NO;
            [self.scanTimer invalidate];
            self.scanTimer = nil;
        }
    }
}
- (void)moveScanLayer:(NSTimer *)timer
{
    CGRect frame = _scanLayer.frame;
    if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
        frame.origin.y = 0;
        _scanLayer.frame = frame;
    }else{
        
        frame.origin.y += 5;
        
        [UIView animateWithDuration:0.1 animations:^{
            _scanLayer.frame = frame;
        }];
    }
}

-(void)stopReading{
    [_captureSession stopRunning];
    _captureSession = nil;
    [_scanLayer removeFromSuperlayer];
    [_boxView removeFromSuperview];
    [_videoPreviewLayer removeFromSuperlayer];
    [self.aView.startBtn setTitle:@"开始" forState:UIControlStateNormal];
}

#pragma mark 开启闪光灯
- (void)turnTorchOn: (id) sender
{
    _isTorchON = !_isTorchON;
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch] && [device hasFlash]){
        
        [device lockForConfiguration:nil];
        if (_isTorchON) {
            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];
        } else {
            [device setTorchMode:AVCaptureTorchModeOff];
            [device setFlashMode:AVCaptureFlashModeOff];
        }
        [device unlockForConfiguration];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
